
  <div class="layui-card">
    <div class="layui-card-body">
      <div class="layui-form-item" style="margin-bottom: 15px;">
        <div class="layui-inline">
          <input type="text" id="searchUser" placeholder="搜索用户名..." class="layui-input" style="width: 250px;">
        </div>
        <div class="layui-inline">
          <button class="layui-btn" id="searchUserBtn"><i class="layui-icon layui-icon-search"></i> 搜索</button>
          <button class="layui-btn layui-btn-primary" id="refreshUserBtn"><i class="layui-icon layui-icon-refresh"></i> 刷新</button>
        </div>
        <div class="layui-inline" style="float: right;">
          <button class="layui-btn" id="addUserBtn"><i class="layui-icon layui-icon-addition"></i> 添加用户</button>
        </div>
      </div>

      <table class="layui-table" lay-skin="line">
        <colgroup>
          <col width="80">
          <col width="200">
          <col width="200">
          <col width="180">
          <col width="180">
          <col width="200">
        </colgroup>
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>所属角色</th>
            <th>创建时间</th>
            <th>最后修改时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody id="userTable">
        </tbody>
      </table>
    </div>
  </div>

<!-- 用户表单 -->
<script type="text/html" id="userFormTpl">
  <form class="layui-form" style="padding: 20px;" lay-filter="userForm">
    <input type="hidden" name="id">
    <div class="layui-form-item">
      <label class="layui-form-label">用户名</label>
      <div class="layui-input-block">
        <input type="text" name="user" required lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item" id="passwordItem">
      <label class="layui-form-label">密码</label>
      <div class="layui-input-block">
        <input type="password" name="password" placeholder="请输入密码" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">所属角色</label>
      <div class="layui-input-block">
        <select name="role" lay-verify="required">
          <option value="">请选择角色</option>
        </select>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn" lay-submit lay-filter="submitUser">保存</button>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
      </div>
    </div>
  </form>
</script>

<script>
// 从后端获取的数据
var userData = [];       // 用户数据
var roleData = [];       // 角色数据

layui.use(['layer', 'form', 'jquery'], function(){
  var layer = layui.layer;
  var form = layui.form;
  var $ = layui.jquery;
  
  // 格式化时间
  function formatTime(timestamp) {
    if (!timestamp) return '-';
    // 如果是时间戳，转换为格式化时间
    var date = new Date(timestamp);
    return date.getFullYear() + '-' + 
           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
           String(date.getDate()).padStart(2, '0') + ' ' +
           String(date.getHours()).padStart(2, '0') + ':' + 
           String(date.getMinutes()).padStart(2, '0') + ':' + 
           String(date.getSeconds()).padStart(2, '0');
  }
  
  // 获取角色名称
  function getRoleName(roleID) {
    var role = roleData.find(function(r) {
      return r.id === roleID;
    });
    return role ? role.name : '未分配角色';
  }
  
  // 从后端获取数据
  function fetchData() {
    // 显示加载提示
    var loading = layer.load(2);
    
    // 获取角色数据
    fetch('/auth/role')
      .then(response => response.json())
      .then(roleResult => {
        if (roleResult.result) {
          roleData = roleResult.data || [];
        }
        
        // 获取用户数据
        return fetch('/auth/user');
      })
      .then(response => response.json())
      .then(userResult => {
        layer.close(loading); // 关闭加载提示
        if (userResult.result) {
          userData = userResult.data || [];
        }
        renderUser();
      })
      .catch(error => {
        layer.close(loading); // 关闭加载提示
        layer.msg('数据加载失败: ' + error.message, {icon: 2});
        console.error('Error:', error);
        // 即使出错也渲染界面，使用现有数据
        renderUser();
      });
  }
  
  // 渲染用户列表
  function renderUser() {
    var tbody = document.getElementById('userTable');
    tbody.innerHTML = '';
    
    var searchValue = document.getElementById('searchUser').value.toLowerCase();
    var filtered = userData.filter(function(user) {
      return user.user.toLowerCase().includes(searchValue);
    });
    
    filtered.forEach(function(user) {
      var tr = document.createElement('tr');
      tr.innerHTML = `
        <td><strong>${user.id}</strong></td>
        <td><strong>${user.user}</strong></td>
        <td><span class="layui-badge layui-bg-blue">${getRoleName(user.role)}</span></td>
        <td>${user.createTime}</td>
        <td>${user.updateTime}</td>
        <td>
          <button class="layui-btn layui-btn-xs layui-btn-normal edit-user" data-id="${user.id}">编辑</button>
          <button class="layui-btn layui-btn-xs layui-btn-warm reset-pwd" data-id="${user.id}">重置密码</button>
          <button class="layui-btn layui-btn-xs layui-btn-danger delete-user" data-id="${user.id}">删除</button>
        </td>
      `;
      tbody.appendChild(tr);
    });
    
    document.querySelectorAll('.edit-user').forEach(function(btn) {
      btn.onclick = function() {
        var id = parseInt(this.getAttribute('data-id'));
        editUser(id);
      };
    });
    
    document.querySelectorAll('.reset-pwd').forEach(function(btn) {
      btn.onclick = function() {
        var id = parseInt(this.getAttribute('data-id'));
        resetPassword(id);
      };
    });
    
    document.querySelectorAll('.delete-user').forEach(function(btn) {
      btn.onclick = function() {
        var id = parseInt(this.getAttribute('data-id'));
        deleteUser(id);
      };
    });
  }
  
  // 填充角色选择框
  function fillRoleSelect(selectElement) {
    selectElement.innerHTML = '<option value="">请选择角色</option>';
    roleData.forEach(function(role) {
      var option = document.createElement('option');
      option.value = role.id;
      option.textContent = role.name;
      selectElement.appendChild(option);
    });
  }
  
  // 添加用户
  function addUser() {
    layer.open({
      type: 1,
      title: '添加用户',
      area: ['520px', '306px'],
      content: document.getElementById('userFormTpl').innerHTML,
      success: function(layero, index) {
        // 修改表单提交按钮的 filter 为唯一值
        var uniqueFilter = 'submitUser-add-' + index;
        layero.find('button[lay-filter="submitUser"]').attr('lay-filter', uniqueFilter);
        
        // 填充角色选择框
        var selectElement = layero.find('select[name="role"]')[0];
        fillRoleSelect(selectElement);
        
        // 确保表单渲染完成后再设置值
        setTimeout(function() {
          form.val('userForm', {
            id: '',
            user: '',
            password: '',
            role: ''
          });
          
          // 密码字段必填
          layero.find('input[name="password"]').attr('lay-verify', 'required').attr('placeholder', '请输入密码（必填）');
          
          // 重新渲染表单
          form.render();
        }, 100);
        
        // 在 success 回调中直接注册事件，使用唯一的 filter
        form.on('submit(' + uniqueFilter + ')', function(data) {
          // 提交新增到后端
          var loading = layer.load(2);
          
          // 准备提交数据
          var submitData = {
            user: data.field.user,
            password: data.field.password,
            role: parseInt(data.field.role)
          };
          
          // 发送POST请求添加用户
          fetch('/auth/user', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(submitData)
          })
          .then(response => {
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
              return response.json();
            } else {
              throw new Error('服务器返回了非JSON格式的响应: ' + response.status + ' ' + response.statusText);
            }
          })
          .then(result => {
            layer.close(loading);
            if (result.result) {
              // 重新获取数据
              fetchData();
              layer.close(index);
              layer.msg('用户已添加');
            } else {
              layer.msg('添加失败: ' + (result.message || result.msg || '未知错误'), {icon: 2});
            }
          })
          .catch(error => {
            layer.close(loading);
            layer.msg('请求失败: ' + error.message, {icon: 2});
            console.error('Error:', error);
          });
          
          return false;
        });
      }
    });
  }
  
  // 编辑用户
  function editUser(id) {
    var user = userData.find(function(u) {
      return u.id === id;
    });
    
    if (!user) {
      layer.msg('用户不存在', {icon: 2});
      return;
    }
    
    layer.open({
      type: 1,
      title: '编辑用户',
      area: ['520px', '250px'],
      content: document.getElementById('userFormTpl').innerHTML,
      success: function(layero, index) {
        // 修改表单提交按钮的 filter 为唯一值
        var uniqueFilter = 'submitUser-edit-' + index;
        layero.find('button[lay-filter="submitUser"]').attr('lay-filter', uniqueFilter);
        
        // 隐藏密码字段（编辑时不允许修改密码）
        layero.find('#passwordItem').hide();
        
        // 填充角色选择框
        var selectElement = layero.find('select[name="role"]')[0];
        fillRoleSelect(selectElement);
        
        // 使用setTimeout确保DOM完全渲染后再设置表单值
        setTimeout(function() {
          form.val('userForm', {
            id: user.id,
            user: user.user,
            role: user.role
          });
          
          // 重新渲染表单
          form.render();
        }, 100);
        
        // 在 success 回调中直接注册事件，使用唯一的 filter
        form.on('submit(' + uniqueFilter + ')', function(data) {
          // 提交修改到后端
          var loading = layer.load(2);
          
          // 准备提交数据
          var submitData = {
            id: parseInt(data.field.id),
            user: data.field.user,
            role: parseInt(data.field.role)
          };
          
          // 发送PUT请求更新用户
          fetch('/auth/user', {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(submitData)
          })
          .then(response => {
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
              return response.json();
            } else {
              throw new Error('服务器返回了非JSON格式的响应: ' + response.status + ' ' + response.statusText);
            }
          })
          .then(result => {
            layer.close(loading);
            if (result.result) {
              // 更新本地数据
              user.user = data.field.user;
              user.role = parseInt(data.field.role);
              user.updateTime = formatTime(new Date());
              
              // 重新渲染
              renderUser();
              layer.close(index);
              layer.msg('用户已更新');
            } else {
              layer.msg('更新失败: ' + (result.message || result.msg || '未知错误'), {icon: 2});
            }
          })
          .catch(error => {
            layer.close(loading);
            layer.msg('请求失败: ' + error.message, {icon: 2});
            console.error('Error:', error);
          });
          
          return false;
        });
      }
    });
  }
  
  // 重置密码
  function resetPassword(id) {
    var user = userData.find(function(u) {
      return u.id === id;
    });
    
    if (!user) {
      layer.msg('用户不存在', {icon: 2});
      return;
    }
    
    layer.prompt({
      formType: 1,
      title: '重置密码 - ' + user.user,
      area: ['400px', '200px']
    }, function(newPassword, promptIndex) {
      if (!newPassword || newPassword.trim() === '') {
        layer.msg('密码不能为空', {icon: 2});
        return;
      }
      
      // 提交密码重置到后端
      var loading = layer.load(2);
      
      // 准备提交数据
      var submitData = {
        id: id,
        password: newPassword
      };
      
      // 发送POST请求重置密码
      fetch('/auth/user/repwd', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(submitData)
      })
      .then(response => {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
          return response.json();
        } else {
          throw new Error('服务器返回了非JSON格式的响应: ' + response.status + ' ' + response.statusText);
        }
      })
      .then(result => {
        layer.close(loading);
        if (result.result) {
          // 更新本地数据的修改时间
          user.updateTime = formatTime(new Date());
          
          // 重新渲染
          renderUser();
          layer.close(promptIndex);
          layer.msg('密码重置成功');
        } else {
          layer.msg('重置失败: ' + (result.message || result.msg || '未知错误'), {icon: 2});
        }
      })
      .catch(error => {
        layer.close(loading);
        layer.msg('请求失败: ' + error.message, {icon: 2});
        console.error('Error:', error);
      });
    });
  }
  
  // 删除用户
  function deleteUser(id) {
    layer.confirm('确定要删除这个用户吗？', {
      icon: 3,
      title: '删除用户'
    }, function(index) {
      // 提交删除到后端
      var loading = layer.load(2);
      
      // 发送DELETE请求删除用户
      fetch('/auth/user?id=' + id, {
        method: 'DELETE'
      })
      .then(response => {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
          return response.json();
        } else {
          throw new Error('服务器返回了非JSON格式的响应: ' + response.status + ' ' + response.statusText);
        }
      })
      .then(result => {
        layer.close(loading);
        if (result.result) {
          userData = userData.filter(function(user) {
            return user.id !== id;
          });
          
          renderUser();
          layer.close(index);
          layer.msg('用户已删除');
        } else {
          layer.msg('删除失败: ' + (result.message || result.msg || '未知错误'), {icon: 2});
        }
      })
      .catch(error => {
        layer.close(loading);
        layer.msg('请求失败: ' + error.message, {icon: 2});
        console.error('Error:', error);
      });
    });
  }
  
  // 事件绑定
  document.getElementById('addUserBtn').onclick = addUser;
  document.getElementById('searchUserBtn').onclick = renderUser;
  document.getElementById('refreshUserBtn').onclick = fetchData;
  
  // 初始化
  fetchData();
});
</script>
